class Campaign < ActiveRecord::Base
  
  has_attached_file :background_image
  has_attached_file :header_image
  has_attached_file :share_image, :styles =>{ :medium => "100x75>" }
  has_attached_file :campaign_image, :styles =>{ :medium => "85x100>" , :small=>"50x50>", :big=>"450x515>"}
  has_many :user_campaigns 
  has_many :campaign_adverts, :dependent => :destroy
  
  
  attr_accessible :name,:is_default, :description,:owner_id,:instructions_to_participate,:instructions_to_win,:start_date,:end_date,
  :prize, :points_invite_friends,:points_submit_content,:points_comment_content,
  :points_vote_content,:invitation_type,:invitation_message,:invitation_content,
  :invitation_action_message,:invitation_land_page_url,
  :publish_wall_join_now_link_text,
  :publish_wall_user_message, :publish_wall_caption,
  :publish_wall_user_message_prompt,:publish_wall_auto_publish,
  :background_image,:header_image,
  :twitter_account_url,:linkedin_account_url,:youtube_account_url,:facebook_account_url,
  :share_title,:share_description,:share_image, :campaign_image,
  :campaign_faq_page_id,:campaign_rules_page_id,:campaign_privacy_page_id,:campaign_tos_page_id,
  :points_content_voted, :points_content_commented,
  :publish_wall_comment_vote_user_content_message,
  :publish_wall_comment_vote_user_content_caption,
  :publish_wall_comment_vote_user_content_link_text,
  :publish_wall_comment_vote_user_content_user_message_prompt,
  :campaign_winner_mail_page_template_id,
  :minimum_points
  
  validates_presence_of :minimum_points, :prize, :points_content_voted, :points_content_commented, :campaign_winner_mail_page_template_id, :campaign_tos_page_id,:campaign_faq_page_id,:campaign_rules_page_id,:campaign_privacy_page_id, :start_date, :end_date, :name, :description, :instructions_to_win, :instructions_to_participate, :owner_id, :points_invite_friends,:points_submit_content,:points_comment_content
  validates_uniqueness_of :name
  
  validate :start_end_date_are_consistent
  
  
  def owner
    User.find(self.owner_id)
  end
  
  
  def active? 
   (Time.zone.today >= self.start_date.to_datetime.to_date ) && (Time.zone.today<=self.end_date.to_datetime.to_date) && !self.ended
  end
  
  def self.has_starting_campaigns?
    Campaign.count(:all, :conditions=>["is_default=:is_default and ended=:ended and start_date > :today",{:today=>Date.today, :ended=>false, :is_default=>false}]) > 0
  end
  
  def self.next_starting_campaigns(count=0)
    if count > 0
      Campaign.find(:all, :limit=>count, :order=>"start_date asc", :conditions=>["is_default=:is_default and ended=:ended and start_date > :today",{:today=>Date.today, :ended=>false, :is_default=>false}])  
    else
      Campaign.find(:all,  :order=>"start_date asc",:conditions=>["is_default=:is_default and ended=:ended and start_date > :today",{:today=>Date.today, :ended=>false, :is_default=>false}])  
    end
  end
  
  def self.has_ended_campaigns?
    Campaign.count(:conditions=>["is_default=:is_default and ended=:ended",{:ended=>true, :is_default=>false}]) > 0
  end
  
  def self.campaigns_for_user(user_id)
    Campaign.find(:all,  :order=>"end_date desc", :conditions=>["user_campaigns.user_id=?",user_id],:joins=>:user_campaigns)
  end
  
  
  def self.ended_campaigns(count=0)
    if  count > 0 
      Campaign.find(:all, :limit=>count, :order=>"end_date desc", :conditions=>["is_default=:is_default and ended=:ended",{:ended=>true, :is_default=>false}])  
    else
      Campaign.find(:all,  :order=>"end_date desc", :conditions=>["is_default=:is_default and ended=:ended",{:ended=>true, :is_default=>false}])  
    end
    
  end
  
  def self.has_active_campaigns?
   (Campaign.count(:conditions=>["is_default=:is_default and :today >= start_date and :today<=end_date and ended=:ended ",{:ended=>false, :today=>Date.today, :is_default=>false}])  > 0)
  end
  
  def self.default_campaign
    Campaign.find_first_by_is_default(true)
  end
  
  def self.active_campaigns(count=0)
    if count > 0
      Campaign.find(:all, :order=>"start_date asc", :limit=>count, :conditions=>["is_default=:is_default and :today >= start_date and :today<=end_date and ended=:ended",{:ended=>false, :today=>Date.today, :is_default=>false}])  
    else
      Campaign.find(:all, :order=>"start_date asc", :conditions=>["is_default=:is_default and :today >= start_date and :today<=end_date and ended=:ended",{:ended=>false, :today=>Date.today, :is_default=>false}])  
    end
    
  end
  
  def participant_count
    UserCampaign.count(:conditions=>"campaign_id=#{self.id} AND is_active=true")
  end
  
  def past_all_participant_count
    UserCampaign.count(:conditions=>"campaign_id=#{self.id}")
  end
  
  def all_user_campaigns
    UserCampaign.find(:all, :conditions=>"campaign_id=#{self.id}", :order=>"points DESC")
  end
  
  def user_campaigns
    UserCampaign.find(:all, :conditions=>"campaign_id=#{self.id} AND is_active=true", :order=>"points DESC")
    
  end
  def self.default_campaign
    Campaign.find_by_is_default(true)
  end
  
  def campaign_tos_page
    Page.find(self.campaign_tos_page_id)
  end
  
  def campaign_faq_page
    Page.find(self.campaign_faq_page_id)
  end
  def campaign_rules_page
    Page.find(self.campaign_rules_page_id)
  end
  def campaign_privacy_page 
    Page.find(self.campaign_privacy_page_id)
  end
  
  def campaign_winner_mail_page_template
    Page.find(self.campaign_winner_mail_page_template_id)
  end
  
  #use the log parameter because this method is called 
  #from backgrounDrb and the logger isn't working
  def self.update_ended_campaigns(log=logger)
    log.info("Updating finished campaigns")
    campaigns = Campaign.find(:all, :conditions=>["is_default=:is_default and :today > end_date and ended=:ended",{:ended=>false, :today=>Date.today, :is_default=>false}])
    for campaign in campaigns
      log.info("Updating campaigns #{campaign.name}")
      campaign.ended = true
      campaign.save!
    end
  end
  
  #this run periodiclly
  def self.notify_winners(log=logger)
    log.info("Notifying winners for ended campaigns")
    #find those campaigns that:
    # - Ended
    # - Have a winner_id > -1
    # - have not notified winner set to true
    campaigns = Campaign.find(:all, :conditions=>["is_default=:is_default and ended=:ended and winner_id > -1 and winner_notified=:notified",{:notified=>false, :ended=>true, :is_default=>false}])
    for campaign in campaigns do
      log.info("Notifying user #{campaign.winner_id} because he's the winner for campaigns #{campaign.name}")
      user = User.find(campaign.winner_id)
      log.info("Winner Name is: #{user.full_name}")
      log.info("Winner email is: #{user.email}")
      UserMailer.deliver_winner_notification(campaign)
      campaign.winner_notified = true
      campaign.save!
    end
  end
  
  private
  def start_end_date_are_consistent
    if self.start_date >= self.end_date
      errors.add(:start_date, "cannot be after or the same as end date")
    end
    
  end
  
end
